<template>
  <div v-page-show="{ show: operate.checkedProject, text: `请选择项目后查看` }">
    <RePage>
      <div class="split-pane">
        <splitpane :splitSet="settingLR">
          <template #paneL>
            <!-- 自定义左侧面板的内容 -->
            <div class="pr-[16px] h-full">
              <treeList ref="treeListRef" :treeProops="treeProops" :treeEvents="treeEvents" :pageShow="false"
                :inputShow="false" />
            </div>
          </template>
          <template #paneR>
            <div class="pl-[20px]">
              <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
                <template #field-groupId="scope">
                  <facilityGrouping v-model="searchFrom.groupId" clearable :placeholder='prompt?.groupId'
                    :style="{ width: '100%' }" @change="(v) => scope.data.model.callback(v)" @clear="getTableList" />
                </template>
                <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
                <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
              </MyFormCreate>
              <div>
                <el-button v-auth="'business.project-facilit.create'" :disabled="drawingIdShow" type="primary"
                  :icon="Plus" @click="add">添加</el-button>
                <el-button v-auth="'business.project-facilit.remove'" type="danger" :icon="Delete"
                  :disabled="!selectionData.length" @click="deletes()">批量删除</el-button>
              </div>
              <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)"
                showOverflowTooltip border @selection-change="selectionChange" :isShowPag="false">
                <template #action="{ row }">
                  <el-space>
                    <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link>
                    <sj-link v-auth="'business.project-facilit.update'" custom-type="sblue" :underline="false"
                      @click="edit(row)">编辑</sj-link>
                    <!-- <sj-link custom-type="sred" :underline="false" @click="deletes(row)">删除</sj-link> -->
                  </el-space>
                </template>
              </pure-table>
              <div class="mt-5">
                <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
                  :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList"
                  @current-change="getTableList" />
              </div>
            </div>
          </template>
        </splitpane>

      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import treeList from '@/components/treeList/treeList.vue'
import splitpane, { ContextProps } from "@/components/ReSplitPane";
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";

import editForm from "./form.vue";
import infos from "./info.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, getInfo, addInfo, editInfo, deleteInfo } from '@/api/operate/project-management/projectManagement/facility-management/index';
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { addDialog } from "@/components/ReDialog";
import { deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { facilitbuildings } from "@/api/operate/timed-tasks/index";
import { customPromiseDebounce } from "@/utils/functions";
import facilityGrouping from '@/components/select/facilityGrouping/facilityGrouping.vue'
import { usePageVariablesStoreHook, } from '@/store/modules/pageVariables'
import { getInfo as settingInfo } from "@/api/operate/project-management/projectManagement/setting";
import { getInfo as drawingInfo, } from '@/api/operate/project-management/project-management/drawing-management/index';


const operate = usePageVariablesStoreHook().getOperate()
const childrenbuilding = ref()
const showBuildingId = ref() //父级的建筑id
const settingLR: ContextProps = reactive({
  minPercent: 17,
  maxPercent: 17,
  defaultPercent: 17,
  split: "vertical"
});
const searchFrom = ref(defaultSearchForm());
const route = useRoute()  // 获取路由参数
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0,
});

const searchFormRules = [
  {
    type: 'input', field: 'facilitName', title: '设施名称', value: null,
    options: facilityGrouping,
    props: {
      placeholder: prompt.facilitName, clearable: true
    }
  },
  {
    type: 'fieldComponent', field: 'groupId', title: titles.groupId, value: null, props: {
      placeholder: prompt.groupId, clearable: true
    }
  },
  {
    type: 'input', field: 'facilitSN', title: titles.facilitSN, value: null, props: {
      placeholder: prompt.facilitSN, clearable: true
    }
  },
  {
    type: 'select', field: 'isWillExpired', title: titles.isWillExpired, value: null,
    options: [
      { label: '即将到期', value: 1 },
      { label: '即将维保', value: 2 },
      { label: '即将报废', value: 3 },
    ],
    props: {
      placeholder: prompt.isWillExpired, clearable: true
    }
  },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];
const selectionData = ref([]);
const roleTableConfig = [
  { type: "selection", align: "left", },

  { prop: 'id', label: titles.id, fixed: 'left', with: 80 },
  { prop: 'facilitName', label: '设施名称', minWidth: 100 },
  { prop: 'facilitSN', label: '点位编号', minWidth: 100 },
  { prop: 'buildingName', label: titles.buildingName, minWidth: 150 },
  { prop: 'groupName', label: titles.groupName, minWidth: 150 },

  { prop: 'createdAt', label: titles.createdAt, minWidth: 160 },
  { slot: 'action', label: titles.action, width: 100, fixed: 'right' },
];
const treeListRef = ref();
const treeRef = ref();
const projectList = ref([]);
const isLoading = ref(true)
const drawingId = ref();
const drawingIdShow = ref(true)
onMounted(() => {
  if (route.query.isWillExpired) {
    searchFrom.value.isWillExpired =Number(route.query.isWillExpired)
    key.value++
  }
  loadProjectList().then(() => {
    treeListRef.value.getTreeRef().setCurrentKey(projectList.value[0].buildingId);
    searchFrom.value.buildingId = projectList.value[0].buildingId
    getTableList()
  })
  // loadProjectList();
  //   getTableList()
  //   treeRef.value = treeListRef.value.getTreeRef();

});

const props = {
  label: "buildingName",
  value: "buildingId",
  children: "children",
  isLeaf: "isLeaf"
};

//树状图
//获取数据

const loadProjectList = () => {
  return new Promise((resolve, reject) => {
    if (operate.checkedProject == null) {
      reject('')
    } else {
      isLoading.value = true;
      facilitbuildings()
        .then(res => {
          let arrs = [
            {
              buildingId: "0",
              buildingName: "全部",
              children: []
            },
            {
              buildingId: "01",
              projectId: res.result.projectId,
              buildingName: "项目平面",
              children: []
            }
          ];
          res.result.buildingInfo.unshift(...arrs);
          res.result.buildingInfo.forEach(item => {
            if (item.children.length > 0) {
              item.children.forEach(item1 => {
                item1.showBuildingId = item.buildingId;
                item1.buildingId = item1.drawingId + "-1" + item.buildingId;

                item1.buildingName = item1.drawingName;
              });
            }


          });
          console.log("day", res.result.buildingInfo);
          projectList.value = res.result.buildingInfo;

        })
        .finally(() => {
          isLoading.value = false;
          resolve('');
        });
    }
  });
};

const handleNodeClick = data => {
  // console.log("点击获取楼层",data);

  console.log(data, data.drawingId);
  if (data.buildingName !== '全部') {
    drawingIdShow.value = false;
  }
  if (data.buildingName !== '项目平面') {
    drawingIdShow.value = false;
  }
  if (data.drawingId == undefined && data.buildingName !== '项目平面') {
    drawingIdShow.value = true;
  }
  childrenbuilding.value = data.buildingId
  drawingId.value = data.drawingId;
  showBuildingId.value = data.showBuildingId;
  // console.log(data, childrenbuilding.value);
  if (drawingId.value !== undefined && drawingId.value !== null && drawingId.value !== '') {
    getImg()
  } else {
    getSettinginfo()
  }

  switch (true) {
    case data.buildingId == "0":
      searchFrom.value.projectId = "";
      searchFrom.value.buildingId = "";
      searchFrom.value.drawingId = "";
      getTableList();
      return;
    case data.buildingId === "01":
      searchFrom.value.projectId = data.projectId;
      searchFrom.value.buildingId = "";
      searchFrom.value.drawingId = "";
      getTableList();
      return;
    case data.drawingId !== undefined:
      searchFrom.value.projectId = "";
      searchFrom.value.buildingId = "";
      searchFrom.value.drawingId = data.drawingId;
      getTableList();
      return;
    case data.buildingId !== 0:
      searchFrom.value.projectId = "";
      searchFrom.value.buildingId = data.buildingId;
      searchFrom.value.drawingId = "";
      getTableList();
      return;
  }

};


const filterMethod = (query, node) => {
  return node.buildingName.includes(query);
};
const treeProops = ref({
  props: props,
  data: projectList,
  "item-size": 46,
  "filter-method": filterMethod,
  nodeKey: "buildingId",
  "highlight-current": true,

});
const treeEvents = {
  nodeClick: handleNodeClick,

};
//获取楼层图纸


const bgImg = ref()
const getImg = () => {
  //如果是室内
  drawingInfo({ id: drawingId.value }).then(res => {

    if (res.code == 200) {

      bgImg.value = res.result.img

      //  console.log("huoss",bgImg.value,res);

    }
  })

}
const getSettinginfo = () => {
  settingInfo().then(res => {
    // console.log("货物设置 projectPlan",res);
    if (res.code == 200) {

      bgImg.value = res.result.projectPlan

    }
  })
}
// 获取列表数据
const getTableList = () => {
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchFrom.value, defaultSearchForm())
  key.value++
  getTableList()
}
// 详情
const info = (row) => {
  addDialog({
    title: `设施详情`,
    hideFooter: true,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoForm()
      }
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          showInfo.value = res.result
          options.props.formInline = res.result
        }
      }).finally(() => {
        options.props.isLoading = false
      })
    },
  });
}
// 新增
const add = () => {
  showInfo.value = {}
  openDialog("添加设施")
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑设施", row)
}
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: row ? [row.id] : selectionData.value.map(item => item.id) }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "添加设施", row?: any) => {
  let sidebar = ref(defaultInfoForm())
  sidebar.value.buildingId = showBuildingId.value
  sidebar.value.drawingId = drawingId.value
  sidebar.value.childrenbuilding = childrenbuilding.value

  if (showBuildingId.value == undefined && drawingId.value == undefined) { //选择全部和平面时所在位置必须是室外
    sidebar.value.position = 2
  } else {
    sidebar.value.position = 1
  }


  // console.log("sidebar", sidebar.value);

  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    props: {
      isLoading: false,
      isEdit: !!row,
      formInline: defaultInfoForm(),
      originMarker: {},
    },
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        // console.log('编辑op',row);
        //       if(drawingId.value !== undefined && drawingId.value !== null && drawingId.value !== ''){
        //   getImg()
        // }else{
        //   getSettinginfo()
        // }

        getInfo({ id: row.id }).then(res => {
          if (res.code == 200) {

            showInfo.value = res.result
            options.props.formInline = res.result
            options.props.formInline.childrenbuilding = childrenbuilding.value
            options.props.originMarker = res.result.drawingPoint
            // console.log('新增op', res);
          }
        }).finally(() => {
          options.props.isLoading = false
        }),
          options.props = {
            isLoading: true,
            isEdit: true,
            formInline: defaultInfoForm(),
            originMarker: {},
            newORedit: 2,

          }
      } else {


        options.props = {
          isLoading: false,
          isEdit: false,
          formInline: sidebar.value,
          newORedit: 1,
          bgImg: bgImg.value,
          originMarker: {},
        }
        options.props.formInline.buildingId = showBuildingId.value
        options.props.formInline.drawingId = drawingId.value
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.projectId = operate.checkedProject
      // console.log("第一层", formData);

      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加设施") {
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped>
.split-pane {
  width: 100%;
  // height: calc(100vh - 200px);
  //   font-size: 50px;
  //   text-align: center;
  //   border: 1px solid #e5e6eb;

  //   .dv-a {
  //     padding-top: 0vh;
  //     color: rgba($color: dodgerblue, $alpha: 80%);
  //   }

  //   .dv-b {
  //     padding-top: 0vh;
  //     color: rgba($color: #000, $alpha: 80%);
  //   }

  //   .dv-c {
  //     padding-top: 0vh;
  //     color: rgba($color: #ce272d, $alpha: 80%);
  //   }
}
</style>
